package com.imjavaj.usfim.freemarker;

import java.io.IOException;
import java.net.URL;

import org.apache.commons.io.FilenameUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import freemarker.cache.URLTemplateLoader;

public class PatternResourceTemplateLoader extends URLTemplateLoader {

    @Override
    protected URL getURL(String name) {
        ResourcePatternResolver resourceLoader = new PathMatchingResourcePatternResolver();
        String template = FilenameUtils.separatorsToUnix(name);

        if (template.startsWith("/")) {
            template = template.substring(1);
        }

        URL templateURL = null;

        try {
            Resource[] resources = resourceLoader.getResources("classpath*:"
                    + template);

            if (resources != null && resources.length > 0) {
                templateURL = resources[0].getURL();
            }
        } catch (IOException e) {
        }

        return templateURL;
    }
}
